"use strict";

const { KError } = require("../utils");
const { MemberModel } = require("../model");
const _ = require("lodash");
const Sequelize = require("sequelize");
const DB = require("./../utils/MysqlDB");

exports.create = async (data) => {
  if (_.isNil(data) || !_.isObject(data))
    throw KError.InvalidFormatData("create func data is Nil");
  const result = await MemberModel.create(data);
  return result;
};

exports.countGroupByStore = async (where) => {
  let sql = "SELECT count(DISTINCT name) count, store from members";
  if (where) {
    sql += ` ${where}`;
  }
  sql += " GROUP BY store";
  const counts = await DB.query(sql, {
    type: Sequelize.QueryTypes.SELECT,
  });
  return counts;
};

exports.count = async (search) => {
  if (_.isNil(search) || !_.isObject(search))
    throw KError.InvalidFormatData("count func search is Nil");
  return await MemberModel.count(search);
};

exports.findAll = async (search) => {
  if (_.isNil(search) || !_.isObject(search))
    throw KError.InvalidFormatData("findAll func search is Nil");
  const result = await MemberModel.findAll(search);
  return result;
};

exports.findOne = async (search) => {
  if (_.isNil(search) || !_.isObject(search))
    throw KError.InvalidFormatData("findOne func search is Nil");
  const result = await MemberModel.findOne(search);
  return result;
};

exports.deleteById = async (id) => {
  if (_.isNil(id)) throw KError.InvalidFormatData("deleteById func id is Nil");
  const result = await MemberModel.destroy({
    where: { id },
  });
  return result;
};

exports.deleteMany = async (search) => {
  if (_.isNil(search) || !_.isObject(search))
    throw KError.InvalidFormatData("deleteMany func search is Nil");
  const result = await MemberModel.destroy(search);
  return result;
};
